package com.jiahao.material.services.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiahao.material.entity.TokenEntity;
import com.jiahao.material.mapper.TokenEntityMapper;
import com.jiahao.material.services.ITokenEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class TokenEntityServiceImpl extends ServiceImpl<TokenEntityMapper, TokenEntity> implements ITokenEntityService {

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Autowired
    private TokenEntityMapper tokenEntityMapper;

    @Override
    public TokenEntity createToken(String uid) {
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        TokenEntity byUid = tokenEntityMapper.selectById(uid);
        if (byUid==null){
            byUid=new TokenEntity();
            byUid.setToken(UUID.randomUUID().toString().replaceAll("-",""));
            byUid.setUid(uid);
            byUid.setUpdateTime(now);
            byUid.setExpireTime(expireTime);
            tokenEntityMapper.insert(byUid);
        }else{
            byUid.setToken(UUID.randomUUID().toString().replaceAll("-",""));
            byUid.setExpireTime(expireTime);
            byUid.setUpdateTime(now);
            tokenEntityMapper.updateById(byUid);
        }
        return byUid;
    }

    @Override
    public void logout(String token) {
        QueryWrapper<TokenEntity> tokenEntityQueryWrapper = new QueryWrapper<>();
        tokenEntityQueryWrapper.eq("token",token);
        TokenEntity byToken = tokenEntityMapper.selectOne(tokenEntityQueryWrapper);
        token=UUID.randomUUID().toString().replaceAll("-","");
        TokenEntity tokenEntity=new TokenEntity();
        tokenEntity.setToken(token);
        tokenEntity.setUid(byToken.getUid());
        tokenEntityMapper.deleteById(byToken.getUid());
        tokenEntityMapper.insert(tokenEntity);
    }
}
